package problem648;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

//648.单词替换
//https://leetcode.cn/problems/replace-words/?envType=problem-list-v2&envId=hash-table

class Solution {
    public String replaceWords(List<String> dictionary, String sentence) {
        Set<String> set = new HashSet<>();
        for(String s : dictionary) {
            set.add(s);
        }
        String[] words = sentence.split(" ");
        StringBuffer ret = new StringBuffer();
        for(String word : words) {
            boolean flag = false;
            for(int i = 0; i<word.length(); i++) {
                String t = word.substring(0, i+1);
                if(set.contains(t)) {
                    ret.append(t);
                    flag = true;
                    break;
                }
            }
            if(!flag) {
                ret.append(word);
            }
            ret.append(" ");
        }
        ret.deleteCharAt(ret.length()-1);
        return ret.toString();
    }
}